package cn.xhjava.crm.workbench.controller;

import cn.xhjava.crm.commons.ReturnObject;
import cn.xhjava.crm.commons.SysContants;
import cn.xhjava.crm.commons.util.*;
import cn.xhjava.crm.settings.domain.User;
import cn.xhjava.crm.settings.service.UserService;
import cn.xhjava.crm.workbench.domain.Activity;
import cn.xhjava.crm.workbench.domain.ActivityRemark;
import cn.xhjava.crm.workbench.service.ActivityRemarkService;
import cn.xhjava.crm.workbench.service.ActivityService;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;

/**
 * Author:   XiaHu
 * Date:     2023/6/27
 * 市场活动
 */
@Controller
public class ActivityController {
    private static final Logger log = LoggerFactory.getLogger(ActivityController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private ActivityService activityService;

    @Autowired
    private ActivityRemarkService activityRemarkService;

    @RequestMapping("/workbench/activity/index")
    public String index(HttpServletRequest request) {
        log.info("跳转到 activity index");
        //调用service层方法，查询所有的用户
        List<User> userList = null;
        try {
            userList = userService.queryAllUsers();
        } catch (Exception e) {
            log.error(ExceptionUtil.getStackTrace(e));
        }
        //把数据保存到request中
        request.setAttribute("userList", userList);
        //请求转发到市场活动的主页面
        return "workbench/activity/index";
    }

    // 新增市场活动
    @RequestMapping("/workbench/activity/add")
    public @ResponseBody
    Object add(Activity activity, HttpSession session) {
        User user = (User) session.getAttribute(SysContants.SESSION_USER);
        //封装参数
        activity.setId(UUIDUtils.getUUID());
        activity.setCreateTime(DateUtils.formateDateTime(new Date()));
        activity.setCreateBy(user.getId());

        ReturnObject returnObject = new ReturnObject();
        try {
            //调用service层方法，保存创建的市场活动
            int ret = activityService.add(activity);

            if (ret > 0) {
                returnObject.setCode(SysContants.RETURN_OBJECT_CODE_SUCCESS);
            } else {
                returnObject.setCode(SysContants.RETURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("系统忙,请稍后重试....");
            }
        } catch (Exception e) {
            log.error(ExceptionUtil.getStackTrace(e));
            returnObject.setCode(SysContants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("系统忙,请稍后重试....");
        }

        return returnObject;
    }

    // 分页查询
    @RequestMapping("/workbench/activity/queryActivitysForPage")
    public @ResponseBody
    Object selectForPage(String name, String owner, String startDate, String endDate,
                         int pageNo, int pageSize, HttpSession session) {
        //封装参数
        Map<String, Object> map = new HashMap<>();
        map.put("name", name);
        map.put("owner", owner);
        map.put("startDate", startDate);
        map.put("endDate", endDate);
        map.put("beginNo", (pageNo - 1) * pageSize);
        map.put("pageSize", pageSize);
        //调用service层方法，查询数据
        List<Activity> activityList = null;
        int totalRows = 0;
        try {
            activityList = activityService.selectForPage(map);
            totalRows = activityService.selectCountForPage(map);
        } catch (Exception e) {
            log.error(ExceptionUtil.getStackTrace(e));
        }

        Map<String, Object> retMap = new HashMap<>();
        retMap.put("activityList", activityList);
        retMap.put("totalRows", totalRows);
        return retMap;
    }

    // 市场活动明细
    @RequestMapping("/workbench/activity/detail")
    public String detail(String id, HttpServletRequest request) {
        //调用service层方法，查询数据
        Activity activity = null;
        try {
            activity = activityService.selectDetailById(id);
        } catch (Exception e) {
            log.error(ExceptionUtil.getStackTrace(e));
        }
        // 根据ActivityId查询ActivityRemark数据
        List<ActivityRemark> remarkList = null;
        try {
            remarkList = activityRemarkService.selectActivityRemarkByActivityId(id);
        } catch (Exception e) {
            log.error(ExceptionUtil.getStackTrace(e));
        }
        //把数据保存到request中
        request.setAttribute("activity", activity);
        request.setAttribute("remarkList", remarkList);
        //请求转发
        return "workbench/activity/detail";
    }

    // 删除
    @RequestMapping("/workbench/activity/delete")
    public @ResponseBody
    Object delete(String[] id) {
        ReturnObject returnObject = new ReturnObject();
        try {
            //调用service层方法，删除市场活动
            int ret = activityService.delete(id);
            if (ret > 0) {
                returnObject.setCode(SysContants.RETURN_OBJECT_CODE_SUCCESS);
            } else {
                returnObject.setCode(SysContants.RETURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("系统忙，请稍后重试....");
            }
        } catch (Exception e) {
            log.error(ExceptionUtil.getStackTrace(e));
            returnObject.setCode(SysContants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("系统忙，请稍后重试....");
        }
        return returnObject;
    }

    // 查询
    @RequestMapping("/workbench/activity/queryById")
    public @ResponseBody
    Object selectById(String id) {
        //调用service层方法，查询市场活动
        Activity activity = null;
        try {
            activity = activityService.selectDetailById(id);
        } catch (Exception e) {
            log.error(ExceptionUtil.getStackTrace(e));
        }
        //根据查询结果，返回响应信息
        return activity;
    }

    // 修改
    @RequestMapping("/workbench/activity/update")
    public @ResponseBody
    Object update(Activity activity, HttpSession session) {
        User user = (User) session.getAttribute(SysContants.SESSION_USER);
        //封装参数
        activity.setEditTime(DateUtils.formateDateTime(new Date()));
        activity.setEditBy(user.getId());

        ReturnObject returnObject = new ReturnObject();
        try {
            //调用service层方法，保存修改的市场活动
            int ret = activityService.update(activity);

            if (ret > 0) {
                returnObject.setCode(SysContants.RETURN_OBJECT_CODE_SUCCESS);
            } else {
                returnObject.setCode(SysContants.RETURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("系统忙，请稍后重试....");
            }
        } catch (Exception e) {
            log.error(ExceptionUtil.getStackTrace(e));
            returnObject.setCode(SysContants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("系统忙，请稍后重试....");
        }

        return returnObject;
    }


    // 导出全部数据
    @RequestMapping("/workbench/activity/exportAllActivitys")
    public void exportAllActivitys(HttpServletResponse response, HttpSession session) {
        User user = (User) session.getAttribute(SysContants.SESSION_USER);
        //封装参数
        List<Activity> activityList = null;
        try {
            activityList = activityService.selectAll();
            HSSFWorkbook wb = new HSSFWorkbook();
            ActivityUtil.exportFile(activityList, wb);
            //把生成的excel文件下载到客户端
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.addHeader("Content-Disposition", "attachment;filename=activityList.xls");
            OutputStream out = response.getOutputStream();
            wb.write(out);
            wb.close();
            out.flush();
        } catch (Exception e) {
            log.error(ExceptionUtil.getStackTrace(e));
        }

    }

    // 导出选择数据
    @RequestMapping("/workbench/activity/exportActivitys")
    public void exportActivitys(HttpServletResponse response, HttpSession session, String[] ids) {
        User user = (User) session.getAttribute(SysContants.SESSION_USER);
        try {
            List<Activity> activityList = activityService.selectList(ids);
            HSSFWorkbook wb = new HSSFWorkbook();
            ActivityUtil.exportFile(activityList, wb);
            //把生成的excel文件下载到客户端
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.addHeader("Content-Disposition", "attachment;filename=activity.xls");
            OutputStream out = response.getOutputStream();
            wb.write(out);
            wb.close();
            out.flush();
        } catch (Exception e) {
            log.error(ExceptionUtil.getStackTrace(e));
        }
    }


    // 导入文件
    @RequestMapping("/workbench/activity/importActivity")
    public @ResponseBody
    Object importActivity(MultipartFile activityFile, String userName, HttpSession session) {
        log.info("username : {}", userName);
        User user = (User) session.getAttribute(SysContants.SESSION_USER);
        ReturnObject returnObject = new ReturnObject();
        try {
            InputStream is = activityFile.getInputStream();
            HSSFWorkbook wb = new HSSFWorkbook(is);
            //根据wb获取HSSFSheet对象，封装了一页的所有信息
            HSSFSheet sheet = wb.getSheetAt(0);//页的下标，下标从0开始，依次增加
            //根据sheet获取HSSFRow对象，封装了一行的所有信息
            HSSFRow row = null;
            HSSFCell cell = null;
            Activity activity = null;
            List<Activity> activityList = new ArrayList<>();
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {//sheet.getLastRowNum()：最后一行的下标
                row = sheet.getRow(i);//行的下标，下标从0开始，依次增加
                activity = new Activity();
                activity.setId(UUIDUtils.getUUID());
                activity.setOwner(user.getId());
                activity.setCreateTime(DateUtils.formateDateTime(new Date()));
                activity.setCreateBy(user.getId());

                for (int j = 0; j < row.getLastCellNum(); j++) {//row.getLastCellNum():最后一列的下标+1
                    //根据row获取HSSFCell对象，封装了一列的所有信息
                    cell = row.getCell(j);//列的下标，下标从0开始，依次增加

                    //获取列中的数据
                    String cellValue = HSSFUtils.getCellValueForStr(cell);
                    if (j == 0) {
                        activity.setName(cellValue);
                    } else if (j == 1) {
                        activity.setStartDate(cellValue);
                    } else if (j == 2) {
                        activity.setEndDate(cellValue);
                    } else if (j == 3) {
                        activity.setCost(cellValue);
                    } else if (j == 4) {
                        activity.setDescription(cellValue);
                    }
                }

                //每一行中所有列都封装完成之后，把activity保存到list中
                activityList.add(activity);
            }
            //调用service层方法，保存市场活动
            int ret = activityService.addList(activityList);
            returnObject.setCode(SysContants.RETURN_OBJECT_CODE_SUCCESS);
            returnObject.setRetData(ret);
        } catch (Exception e) {
            log.error(ExceptionUtil.getStackTrace(e));
            returnObject.setCode(SysContants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("系统忙，请稍后重试....");
        }

        return returnObject;
    }

    @RequestMapping("/workbench/activity/queryActivityLikeName")
    public @ResponseBody
    Object selectLikeName(String activityName) {
        List<Activity> activity = null;
        try {
            activity = activityService.selectLikeName(activityName);
        } catch (Exception e) {
            log.error(ExceptionUtil.getStackTrace(e));
        }
        return activity;
    }

    @RequestMapping("/workbench/activity/queryActivityByNameAndClueId")
    public @ResponseBody
    Object selectActivityByNameAndClueId(String activityName, String clueId, HttpSession session) {
        Map<String, Object> map = new HashMap<>();
        map.put("activityName", activityName);
        map.put("clueId", clueId);
        List<Activity> activityList = null;
        try {
            activityList = activityService.selectActivityByNameAndClueId(map);
        } catch (Exception e) {
            log.error(ExceptionUtil.getStackTrace(e));
        }
        return activityList;
    }

    @RequestMapping("/workbench/activity/queryActivityByNameAndContactsId")
    public @ResponseBody
    Object selectActivityByNameAndContactsId(String activityName, String contactsId) {
        //封装参数
        Map<String, Object> map = new HashMap<>();
        map.put("activityName", activityName);
        map.put("contactsId", contactsId);
        List<Activity> activityList = null;
        try {
            activityList = activityService.selectActivityByNameAndContactsId(map);
        } catch (Exception e) {
            log.error(ExceptionUtil.getStackTrace(e));
        }
        return activityList;
    }
}
